<template>
  <div class="app-container">
    <el-form
      size="small"
      :inline="true"
      ref="form"
      :model="form"
      label-width="50px"
    >
      <el-form-item label="油企" v-if="false">
        <el-select
          v-model="form.enterpriseId"
          :clearable="true"
          filterable
          placeholder="请选择油企"
          style="width: 260px; margin-left: 10px"
          @change="handleSelectChange"
        >
          <el-option
            v-for="(item, index) in enterpriseList"
            :key="index"
            :value="item.enterpriseId"
            :label="item.enterpriseName"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="油站"
        v-if="!['2'].includes($store.state.user.userLevel)"
      >
        <el-select
          v-model="form.stationId"
          :clearable="true"
          filterable
          placeholder="请选择油站"
          style="width: 260px; margin-left: 10px"
        >
          <el-option
            v-for="item in stationList"
            :key="item.stationId"
            :label="item.stationName"
            :value="item.stationId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="名称">
        <el-select
          :clearable="true"
          filterable
          style="width: 220px"
          v-model="form.payType"
          placeholder="请选择名称"
        >
          <el-option
            v-for="item in payTypeNameList"
            :key="item.payType"
            :label="item.payTypeName"
            :value="item.payType"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="时间">
        <el-date-picker
          style="margin-right: 10px"
          v-model="form.beginTime"
          type="datetime"
          placeholder="选择起始时间"
        >
        </el-date-picker>
        <el-date-picker
          v-model="form.endTime"
          type="datetime"
          placeholder="选择结束时间"
        >
        </el-date-picker>
      </el-form-item>

      <el-row
        class="global_el_rowStyle"
        :gutter="10"
        style="
          border-top: none;
          border-bottom: 1px solid #f5f5f5;
          margin-top: -20px;
        "
      >
        <el-col :span="1.5">
          <el-button
            type="primary"
            size="mini"
            @click="querying"
            v-if="['1', '2'].includes($store.state.user.userLevel)"
            >查询</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-if="['1'].includes($store.state.user.userLevel)"
            type="primary"
            size="mini"
            plain
            @click="newAdditions"
            >新增</el-button
          >
        </el-col>
      </el-row>
    </el-form>
    <el-table
      style="margin-top: 20px; width: 100%"
      :data="payTypeList"
      border
      v-loading="loading"
    >
      <el-table-column label="序号" type="index" align="left" width="70" />
      <el-table-column
        prop="enterpriseName"
        label="油企"
        align="left"
        v-if="!['2'].includes($store.state.user.userLevel)"
      >
      </el-table-column>
      <el-table-column prop="stationName" label="使用油站" align="left">
      </el-table-column>
      <el-table-column prop="payTypeName" label="名称" align="left">
      </el-table-column>
      <el-table-column prop="addTime" label="添加时间" align="left">
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="120" align="left">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            v-show="
              scope.row.isEdit == '0' &&
              ['1'].includes($store.state.user.userLevel)
            "
            @click="payTypeEditing(scope.row)"
            >编辑</el-button
          >

          <el-popconfirm
            title="是否删除？"
            confirm-button-text="删除"
            @onConfirm="payTypeDelete(scope.row)"
          >
            <el-button
              style="margin-left: 15px"
              slot="reference"
              type="text"
              size="small"
              v-show="
                scope.row.isEdit == '0' &&
                ['1'].includes($store.state.user.userLevel)
              "
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 20px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="form.pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="form.pageSize"
      layout="->,total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <el-drawer
      size="40%"
      :title="titleName"
      :visible.sync="drawer"
      :before-close="handleClose"
    >
      <el-form
        :model="formDrawer"
        :rules="formDrawerRules"
        ref="formDrawerRef"
        size="small"
        label-width="80px"
        style="margin: 0px 30px 0px 10px; position: relative"
      >
        <el-form-item prop="payTypeName">
          <label slot="label"><span style="color: red">*</span> 名称</label>
          <el-input v-model="formDrawer.payTypeName" maxlength="255"></el-input>
        </el-form-item>
        <el-form-item label="可用油站" prop="stationId">
          <el-select
            v-model="formDrawer.stationId"
            :clearable="true"
            filterable
            placeholder="请选择油站"
            style="width: 100%"
          >
            <el-option
              v-for="item in stationList"
              :key="item.stationId"
              :label="item.stationName"
              :value="item.stationId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <div style="position: absolute; right: 0px">
          <el-button
            type="primary"
            size="small"
            @click="submitFormSave('formDrawerRef')"
            >保存</el-button
          >
          <el-button
            type="info"
            size="small"
            @click="NewCancel('formDrawerRef')"
            >取消</el-button
          >
        </div>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import { cloneDeep } from "lodash";
import { enterpriseList } from "@/api/station/orderHistory";
import {
  listEnterpriseStation,
  payTypeName,
  payTypeList,
  payTypeSave,
  payTypeUpdate,
  payTypeListDelete,
} from "@/api/dept";
export default {
  name: "MethodPayment",
  data() {
    var validatePass = (rule, value, callback) => {
      const value1 = cloneDeep(value);
      if (value1.trim()) {
        callback();
      } else {
        callback(new Error("请输入名称"));
      }
    };
    return {
      loading: false,
      titleName: null,
      payTypeList: [],
      total: null,
      // 油企列表
      enterpriseList: [],
      // 油站列表
      stationList: [],
      // 名称列表
      payTypeNameList: [],
      drawer: false,
      formDrawer: {
        id: null,
        payTypeName: null,
        stationId: null,
      },
      form: {
        pageNum: 1,
        pageSize: 10,
        enterpriseId: null,
        stationId: null,
        payType: null,
        beginTime: null,
        endTime: null,
      },
      formDrawerRules: {
        payTypeName: [{ validator: validatePass, trigger: "change" }],
        stationId: [
          { required: true, message: "请选择油站", trigger: "change" },
        ],
      },
    };
  },

  created() {
    let userLevel = this.$store.state.user.userLevel;
    if (["1"].includes(userLevel)) {
      this.form.enterpriseId = this.presentEnterprise.enterpriseId;
    }
    if (["2"].includes(userLevel)) {
      this.form.stationId = this.$store.state.user.stationId;
    }
    this.getStationList(this.presentEnterprise.enterpriseId);
    this.getPayTypeName();
    this.getEnterpriseList();
    this.getPayTypeList();
  },

  methods: {
    // 编辑
    payTypeEditing(row) {
      this.titleName = "编辑支付方式";
      this.drawer = true;
      this.formDrawer.id = row.id;
      this.formDrawer.payTypeName = row.payTypeName;
      this.formDrawer.stationId = row.stationId;
    },

    // 新增取消
    NewCancel(formDrawerRef) {
      this.drawer = false;
      this.$refs[formDrawerRef].resetFields();
    },
    // 新增保存
    submitFormSave(formDrawerRef) {
      this.$refs[formDrawerRef].validate((valid) => {
        if (valid) {
          if (this.formDrawer.id) {
            this.payTypeUpdate();
          } else {
            this.payTypeSave();
          }
        } else {
          return false;
        }
      });
    },

    // 新增请求
    payTypeSave() {
      payTypeSave(this.formDrawer).then((res) => {
        if (res && res.code === 200) {
          this.drawer = false;
          this.getPayTypeList();
          this.$message.success(res.msg);
          this.getPayTypeName();
        } else {
          this.$message.error(res.msg);
        }
      });
    },

    // 编辑
    payTypeUpdate() {
      payTypeUpdate(this.formDrawer).then((res) => {
        if (res && res.code === 200) {
          this.drawer = false;
          this.getPayTypeList();
          this.$message.success(res.msg);
          this.getPayTypeName();
        } else {
          this.$message.error(res.msg);
        }
      });
    },

    // 点击删除
    payTypeDelete(row) {
      payTypeListDelete({ id: row.id }).then((res) => {
        if (res && res.code === 200) {
          if (this.payTypeList.length === 1) {
            this.form.pageNum = 1;
            this.form.pageSize = 10;
          }
          this.getPayTypeList();
          this.$message.success(res.msg);
          this.getPayTypeName();
        } else {
          this.$message.error(res.msg);
        }
      });
    },

    // 点击查询
    querying() {
      this.form.pageNum = 1;
      this.form.pageSize = 10;
      this.getPayTypeList();
    },

    //获取列表
    getPayTypeList() {
      let userLevel = this.$store.state.user.userLevel;
      if (["", null].includes(userLevel)) return;
      this.loading = true;
      this.form.enterpriseId = this.presentEnterprise.enterpriseId;
      const payType = this.form.payType ? this.form.payType : null;
      payTypeList({ ...this.form, payType })
        .then((res) => {
          this.total = res.data.total;
          this.payTypeList = res.data.list;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },

    // 获取名称
    getPayTypeName() {
      let userLevel = this.$store.state.user.userLevel;
      if (["", null].includes(userLevel)) return;
      const enterpriseId = this.form.enterpriseId
        ? this.form.enterpriseId
        : this.presentEnterprise?.enterpriseId;
      const stationId = this.form.stationId
        ? this.form.stationId
        : this.$store.state.user.stationId;
      payTypeName({ enterpriseId, stationId }).then((res) => {
        this.payTypeNameList = res.data;
      });
    },
    // 查询油企
    getEnterpriseList() {
      enterpriseList().then((res) => {
        this.enterpriseList = res.rows;
      });
    },

    // 油企选择
    handleSelectChange(value) {
      this.stationList = [];
      this.form.stationId = null;
      this.getStationList(value);
    },

    // 查询油站
    getStationList(val) {
      const enterpriseId = val ? val : this.presentEnterprise.enterpriseId;
      listEnterpriseStation({ enterpriseId, status: "1" }).then((res) => {
        this.stationList = res;
        // 判断单站，多站
        this.formDrawer.stationId = res[0].stationId;
        if (res.length === 1) {
          this.form.stationId = res[0].stationId;
        } else {
          this.form.stationId = null;
        }
      });
    },

    // 点击新增
    newAdditions() {
      this.formDrawer.id = null;
      this.formDrawer.payTypeName = null;
      this.titleName = "新增支付方式";
      this.drawer = true;
      this.getStationList();
      this.$nextTick(() => {
        this.$refs.formDrawerRef.clearValidate();
      });
    },

    // 新增框关闭
    handleClose(done) {
      done();
      this.$nextTick(() => {
        this.$refs.formDrawerRef.resetFields();
      });
    },

    handleSizeChange(val) {
      this.form.pageSize = val;
      this.getPayTypeList();
    },
    handleCurrentChange(val) {
      this.form.pageNum = val;
      this.getPayTypeList();
    },
  },
};
</script>

<style scoped lang="scss"></style>
